/**
 * 
 */
package com.exemplo.flickrsocial.service;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.exemplo.flickrsocial.util.ImageUtils.DownloadedDrawable;
import com.exemplo.flickrsocial.view.FlickrHelper;
import com.exemplo.flickrsocial.view.FlickrSocial;
import com.gmail.yuyang226.flickr.Flickr;
import com.gmail.yuyang226.flickr.oauth.OAuth;
import com.gmail.yuyang226.flickr.oauth.OAuthToken;
import com.gmail.yuyang226.flickr.people.User;

public class LoadUserTask extends AsyncTask<OAuth, Void, User> {
	/**
	 * 
	 */
	private final FlickrSocial FlickrSocial;
	private ImageView userIconImage;

	public LoadUserTask(FlickrSocial flickrjAndroidSampleActivity,
			ImageView userIconImage) {
		this.FlickrSocial = flickrjAndroidSampleActivity;
		this.userIconImage = userIconImage;
	}

	/**
	 * The progress dialog before going to the browser.
	 */
	private ProgressDialog mProgressDialog;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		mProgressDialog = ProgressDialog.show(FlickrSocial, "",
				"Loading user information...");
		mProgressDialog.setCanceledOnTouchOutside(true);
		mProgressDialog.setCancelable(true);
		mProgressDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dlg) {
				LoadUserTask.this.cancel(true);
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected User doInBackground(OAuth... params) {
		OAuth oauth = params[0];
		User user = oauth.getUser();
		OAuthToken token = oauth.getToken();
		try {

			Flickr f = FlickrHelper.getInstance().getFlickrAuthed(
					token.getOauthToken(), token.getOauthTokenSecret());
			return f.getPeopleInterface().getInfo(user.getId());

		} catch (Exception e) {
			Toast.makeText(FlickrSocial, e.toString(), Toast.LENGTH_LONG)
					.show();
			Log.e(e.toString(), e.getLocalizedMessage());
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(User user) {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
		if (user == null) {
			return;
		}
		FlickrSocial.setUser(user);
		if (user.getBuddyIconUrl() != null) {
			String buddyIconUrl = user.getBuddyIconUrl();
			if (userIconImage != null) {
				ImageDownloadTask task = new ImageDownloadTask(userIconImage);
				Drawable drawable = new DownloadedDrawable(task);
				userIconImage.setImageDrawable(drawable);
				task.execute(buddyIconUrl);
			}
		}
	}

}